﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Server;
using SuperSocket.SocketBase;
using Common.NetWork;
using Common;
using Common.Handle;
using Common.Package;
using MySql.Data.MySqlClient;
using Common.Mysql;
using System.Timers;
using Common.ConsoleSysMessages;
using LoginServer.Command;
//using Common.WPFLuaFramework;

namespace LoginServer.Server
{
    /// <summary>
    /// 登录服务器
    /// </summary>
    public class LoginServer
    {
        private static LoginServer m_instance;
        private MapleServer m_Server;

        /// <summary>
        /// 存放包头
        /// </summary>
        private PacketProcessor m_Processor;

        public static LoginServer Instance
        {
            get
            {
                return m_instance;
            }
            set
            {
                m_instance = value;
            }
        }

        public LoginServer(int port)
        {
            Console.Title = "登录服务器";
            m_Server = new MapleServer();

            SuperSocket.SocketBase.Config.ServerConfig config = new SuperSocket.SocketBase.Config.ServerConfig();
            SuperSocket.SocketBase.Config.RootConfig LConfig = new SuperSocket.SocketBase.Config.RootConfig();
            LConfig.Isolation = IsolationMode.AppDomain;
            LConfig.PerformanceDataCollectInterval = 1000;
            config.Name = "LoginServer";
            config.Port = port;


            //注册事件
            RegisterEvent();

            if (!m_Server.Setup(LConfig, config))
            {
                Console.WriteLine("端口设置失败!");
                Console.ReadKey();
                return;
            }


            /*
             * 
            Common.Mysql.MysqlPool.MysqlConnectPool.GetInstance("server=localhost;user id=root;password=maplestory;database=MapleSuper",Common.Mysql.MysqlPool.ConnectionType.MySql).StartServices();

            #region 数据库连接池使用
            string Name = "5555";
            string pass = "1111";
            string email = "2222";
            byte Sex = 1;

            string com = "insert into accounts(name,password,email,gender) values('" + Name + "','" + pass + "','" + email + "'," + Sex + ");";
            //MapleMySqlManager.m_Ins.GetMysqlCom(com);
            //MapleMySqlManager m_myq = Common.Mysql.MysqlPool.MysqlConnectPool.GetInstance().GetConnection(1111);
            //if (m_myq != null)
            //{
            //    m_myq.GetMysqlCom(com);

            //    m_myq.GetMysqlCom(com);

            //    m_myq.GetMysqlCom(com);
            //}
            #endregion

            */

            //Common.Mysql.MysqlPool.MysqlConnectPool.GetInstance().GetConnection(1111).GetMysqlCom(com);

            //新连接事件
            m_Server.NewSessionConnected += new SessionHandler<MapleSession>(NewSessionConnected);//new SessionHandler<AppSession>(NewSessionConnected);

            //收到消息事件
            m_Server.NewRequestReceived += NewRequestReceived;//new RequestHandler<MapleSession, MpaleRequestInfo>(NewRequestReceived);

            //连接断开事件
            m_Server.SessionClosed += new SessionHandler<MapleSession, SuperSocket.SocketBase.CloseReason>(SessionClosed);


            if (!m_Server.Start())
            {
                Console.WriteLine("启动服务失败!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("登陆服务器开启成功!");
        }

        /// <summary>
        /// 用户断开连接
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        private void SessionClosed(MapleSession session, CloseReason value)
        {
            //switch (value)
            //{
            //    case CloseReason.ClientClosing://客户端主动断开连接
            //    case CloseReason.ServerClosing://服务端主动断开客户端的连接
            //    case CloseReason.TimeOut://时间超时
            //}
            Console.WriteLine("用户:" + session.LocalEndPoint.Address + ":" + session.LocalEndPoint.Port + "断开连接   状态:" + value);
        }

        private void NewRequestReceived(MapleSession session, MpaleRequestInfo requestInfo)
        {
            if (m_Processor.GetHandler(requestInfo.PackageHead) == null)
            {
                Console.WriteLine("包头[" + requestInfo.PackageHead + "] :" + requestInfo.Buffer);
            }
            else
            {
                Console.WriteLine("[服务端]:" + "[" + requestInfo.Key + "] " + requestInfo.Buffer.ToString());
                m_Processor.GetHandler(requestInfo.PackageHead).HandlePacket(WorldServer.Server.MapleWorldServer.GetClinet(session), requestInfo.Buffer);
            }
        }

        /// <summary>
        /// 新用户连接
        /// </summary>
        /// <param name="session"></param>
        private void NewSessionConnected(MapleSession session)
        {
            Console.WriteLine("发现新连接:" + session.ToString());

            byte[] ivRecv = { 70, 114, 122, 82 };
            byte[] ivSend = { 82, 48, 120, 115 };
            //ivRecv[3] = (byte)(int)(Math.random() * 255.0);
            //ivSend[3] = (byte)(int)(Math.random() * 255.0);

            MapleAESOFB sendCypher = new MapleAESOFB(ivSend, 0xFFFF - ServerConstants.MAPLE_VERSION);
            MapleAESOFB recvCypher = new MapleAESOFB(ivRecv, ServerConstants.MAPLE_VERSION);

            WorldServer.Server.MapleWorldServer.AddClient(new MapleClient(session, recvCypher, sendCypher));

            session.Send(MapleLoginPacket.GetHello(27, ivSend, ivRecv));
        }

        /// <summary>
        /// 注册封包事件
        /// </summary>
        public void RegisterEvent()
        {
            m_Processor = new PacketProcessor();
            //m_Processor.registerHandler(RecvPacketOpcode.帐号登录, new MapleLoginHandle());
            //m_Processor.registerHandler(RecvPacketOpcode.帐号注册, new MapleRegisterUIHandle());
            //m_Processor.registerHandler(RecvPacketOpcode.帐号检测, new MapleCheckAccountsHandle());
            //m_Processor.registerHandler(RecvPacketOpcode.注册处理, new MapleRegisterHandle());
            //m_Processor.registerHandler(RecvPacketOpcode.服务器状态, new MapleServerStateHandle());            
        }

        public void CloseServer()
        {
            m_Server.Stop();
            System.Console.WriteLine("登录服务器已停止工作成功!!");
        }

        static void Main(string[] args)
        {

            System.Console.Title = "C#服务端!!";

            ConsoleCommandManager.GetInstance().RegisterCommand(new CLoginCommand());

            while (true)
            {
                string Name = "";
                Name = Console.ReadLine();
                string[] pr = Name.Split(' ');

                ConsoleCommandManager.GetInstance().Call(pr[0], pr);
            }
        }
    }
}
